<template>
  <div class="app-container">
    <div v-if="show">
      <el-form :model="queryParams" ref="queryForm" :inline="true" size="small" v-show="showSearch" label-width="68px">
        <el-form-item label="客户名称" prop="sendUserName">
          <el-input
            v-model="queryParams.sendUserName"
            placeholder="请输入客户名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="messageConversationList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" align="center" type="index"/>
        <el-table-column label="客户名称" align="center" prop="sendUserName">
          <template slot-scope="scope">
            <div @click="chatDetail(scope.row)" style="cursor: pointer;color:#1c84c6;">{{
                scope.row.sendUserName
              }}
            </div>
            <div class="num" v-if="scope.row.receiveUnreadCount >= 1">
              <span v-if="scope.row.receiveUnreadCount >= 100">99+</span>
              <span v-else>{{ scope.row.receiveUnreadCount }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="客户类型" align="center" prop="userType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_type" :value="scope.row.userType"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="客服名称" align="center" prop="receiveUserName"/>
        <el-table-column label="咨询时间" align="center" prop="updateTime"/>
      </el-table>
    </div>
    <div v-else style="display: flex; width: 100%;">

      <div class="left">
        <div class="chat-area">
          <div class="right-chat-box">
            <div class="nav-title">
              <span class="red-circle" v-show="circle"></span>
              <i class="el-icon-arrow-left" style="font-weight: 700; font-size: 26px;" @click="showList"></i>
              <div>{{ sendUserName }}</div>
            </div>
            <div class="r-item show">
              <div id="chat-area" v-scroll="{auto: true}">
                <div v-for="(item, i) in messageLogList" :key="i">
                  <div v-if="item.sendUserId !== userId" class="item item-left">
                    <div class="avatar">
                      <img :src="item.sendUserAvatar" onerror="this.src = 'https://peiyiwang.obs.cn-east-3.myhuaweicloud.com/file%2F61561121440571.jpg'">
                    </div>
                    <div style="font-size: 1px; margin-left: 14px;">{{ item.createTime }}</div>
                    <br/>
                    <div class="item-content" v-if="item.type === '1'">{{ item.content }}</div>
                    <div class="item-content" v-if="item.type === '2'">
                      <el-image
                        style="width: 100px; height: 100px;"
                        :src="item.content"
                        class="avatar"
                        :preview-src-list="new Array(item.content)"
                      >
                      </el-image>
                    </div>
                    <div class="item-content file" v-if="item.type === '3'">
                      <!--                      <div @click="clickThis(item.content,item.remark)" style="cursor: pointer" >-->
                      <!--                        <div v-if="item.fileType === 'doc' || item.fileType === 'docx'">-->
                      <!--                          <img src="../../../assets/image/word@2x.png">-->
                      <!--                        </div>-->
                      <!--                        <div v-if="item.fileType === 'xlsx' || item.fileType === 'xls'">-->
                      <!--                          <img src="../../../assets/image/excel@2x.png">-->
                      <!--                        </div>-->
                      <!--                        <div v-if="item.fileType === 'ppt' || item.fileType === 'pptx'">-->
                      <!--                          <img src="../../../assets/image/ppt@2x.png">-->
                      <!--                        </div>-->
                      <!--                        <div v-if="item.fileType === 'pdf'">-->
                      <!--                          <img src="../../../assets/image/pdf@2x.png">-->
                      <!--                        </div>-->
                      <!--                        <div v-if="item.fileType === 'wav'">-->
                      <!--                          <img src="../../../assets/image/wav@2x.png">-->
                      <!--                        </div>-->
                      <!--                        <div v-if="item.fileType !== 'doc' && item.fileType !== 'docx' && item.fileType !== 'xlsx'  && item.fileType!== 'xls' && item.fileType !== 'ppt' && item.fileType !== 'pptx' && item.fileType !== 'pdf' && item.fileType !== 'wav'">-->
                      <!--                          <img src="../../../assets/image/other@2x.png" >-->
                      <!--                        </div>-->
                      <!--                        <div class="remark ellipses-one">-->
                      <!--                          {{item.remark}}-->
                      <!--                        </div>-->
                      <!--                      </div>-->
                    </div>
                  </div>
                  <div v-else class="item item-right">
                    <div class="avatar">
                      <img :src="item.sendUserAvatar" onerror="this.src = 'https://peiyiwang.obs.cn-east-3.myhuaweicloud.com/file%2F61561121440571.jpg'">
                    </div>
                    <div style="font-size: 1px; margin-right: 14px;">{{ item.createTime }}</div>
                    <br/>
                    <div class="item-content" v-if="item.type === '1'">{{ item.content }}</div>
                    <div class="item-content" v-if="item.type === '2'">
                      <el-image
                        style="width: 100px; height: 100px;"
                        :src="item.content"
                        class="avatar"
                        :preview-src-list="new Array(item.content)"
                      >
                      </el-image>
                    </div>
                    <div class="item-content file" v-if="item.type === '3'">
                      <!--                      <div @click="clickThis(item.content,item.remark)" style="cursor: pointer">-->
                      <!--                        <div v-if="item.fileType === 'doc' || item.fileType === 'docx'">-->
                      <!--                          <img src="../../../assets/image/word@2x.png">-->
                      <!--                        </div>-->
                      <!--                        <div v-if="item.fileType === 'xlsx' || item.fileType === 'xls'">-->
                      <!--                          <img src="../../../assets/image/excel@2x.png">-->
                      <!--                        </div>-->
                      <!--                        <div v-if="item.fileType === 'ppt' || item.fileType === 'pptx'">-->
                      <!--                          <img src="../../../assets/image/ppt@2x.png">-->
                      <!--                        </div>-->
                      <!--                        <div v-if="item.fileType === 'wav'">-->
                      <!--                          <img src="../../../assets/image/wav@2x.png">-->
                      <!--                        </div>-->
                      <!--                        <div v-if="item.fileType === 'pdf'">-->
                      <!--                          <img src="../../../assets/image/pdf@2x.png">-->
                      <!--                        </div>-->
                      <!--                        <div v-if="item.fileType !== 'doc' && item.fileType !== 'docx' && item.fileType !== 'xlsx'  && item.fileType !== 'xls' && item.fileType !== 'ppt' && item.fileType !== 'pptx' && item.fileType !== 'pdf' && item.fileType !== 'wav'">-->
                      <!--                          <img src="../../../assets/image/other@2x.png" >-->
                      <!--                        </div>-->
                      <!--                        <div class="remark ellipses-one">-->
                      <!--                          {{item.remark}}-->
                      <!--                        </div>-->
                      <!--                      </div>-->
                    </div>
                  </div>
                </div>
              </div>
              <div class="upload-box">
                <el-upload
                  ref="upload"
                  action="#"
                  disabled="disabled"
                  :show-file-list="false"
                  :headers="picupload.headers"
                  :action="picupload.url"
                  :disabled="picupload.isUploading"
                  :on-progress="handleChatUploadProgress"
                  :on-success="handleChatSuccess"
                  :auto-upload="true"
                  name="multipartFile"
                  accept="image/*"
                  v-if="userId != 1"
                  drag
                >
                  <div>
                    <i class="el-icon-picture"></i>
                  </div>
                </el-upload>
                <!--                <el-upload-->
                <!--                  ref="upload"-->
                <!--                  action="#"-->
                <!--                  disabled="disabled"-->
                <!--                  :show-file-list="false"-->
                <!--                  :headers="picupload.headers"-->
                <!--                  :action="picupload.url"-->
                <!--                  :disabled="picupload.isUploading"-->
                <!--                  :on-progress="handleUploadProgress"-->
                <!--                  :on-success="handleSuccessV2"-->
                <!--                  :auto-upload="true"-->
                <!--                  name = "multipartFile"-->
                <!--                  v-if="userId != 1"-->
                <!--                  accept="application/msword,application/pdf,application/vnd.ms-excel,application/msexcel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,audio/*"-->
                <!--                  drag>-->
                <!--                  <div>-->
                <!--                    <i class="el-icon-document"></i>-->
                <!--                  </div>-->
                <!--                </el-upload>-->
              </div>

              <div class="text-area" style="margin-top: 2px;">
                <textarea placeholder="请输入..." class="soc-txt" v-model="chatTxt" @keyup.enter="sendMessage"
                          maxlength="200"
                          @input="descInput"
                          v-if="userId != 1"
                ></textarea>
                <div style="text-align: right;margin-top: 15px" v-if="userId !== 1">
                  <span>您还可以输入{{ txtVal }}个字,最多输入200字</span>
                </div>
              </div>
              <div class="orderBtn" style="cursor: pointer;float: left" @click="helpCustomerOrder" v-hasPermi="['biz:serviceOrder:helpCustomerOrder']">代客户下单</div>
              <div class="btn" style="cursor: pointer;" @click="sendMessage" v-if="userId != 1">发 送</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-drawer
      title="代客户下单"
      :visible.sync="helpOrderOpen"
      size="45%"
      :show-close="true"
      :wrapperClosable="false"
    >
      <el-form ref="helpOrderForm" :model="helpOrderForm" :rules="rules" label-width="80px" style="margin-left: 25px">
        <el-form-item label="服务类型" prop="orderType">
          <el-select placeholder="请选择服务类型" v-model="helpOrderForm.orderType" style="width: 50%" @change="selectServiceUser">
            <el-option label="陪诊" value="20"></el-option>
            <el-option label="护理" value="30"></el-option>
            <el-option label="问诊" value="40"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务人员" prop="acceptUserId">
          <el-select v-model="helpOrderForm.acceptUserId" placeholder="请选择服务人员" style="width: 50%" filterable @change="clearProductInfo">
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="购买类型" prop="buyType">
          <el-select placeholder="请选择购买类型" v-model="helpOrderForm.buyType" style="width: 50%" @change="selectServiceList">
            <el-option label="服务" value="1"></el-option>
            <el-option label="套餐" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择服务" prop="productId" v-if="helpOrderForm.buyType === '1'" >
          <el-select v-model="helpOrderForm.productId" placeholder="请选择服务" style="width: 50%" filterable @change="selectHospital">
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择套餐" prop="productId" v-if="helpOrderForm.buyType === '2'" >
          <el-select v-model="helpOrderForm.productId" placeholder="请选择套餐" style="width: 50%" filterable @change="selectHospital">
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约医院" prop="hospitalId">
          <el-select v-model="helpOrderForm.hospitalId" placeholder="请选择预约医院" style="width: 50%" filterable>
            <el-option
              v-for="item in hospitalList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentDate" >
          <el-date-picker
            style="width: 50%"
            v-model="helpOrderForm.appointmentDate"
            type="datetime"
            placeholder="选择预约时间"
            value-format="yyyy-MM-dd HH:mm"
            align="right"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单金额" prop="amount" >
            <el-input v-model="helpOrderForm.amount" placeholder="请输入订单金额" style="width: 50%" disabled>
              <template slot="append">陪护豆</template>
            </el-input>
        </el-form-item>
        <el-form-item label="订单数量" prop="num" >
          <el-input-number v-model="helpOrderForm.num"  :min="1" :max="99" @change="handleAddAmount" label="请选择订单数量" @keydown.native="channelInputLimit" ></el-input-number>
        </el-form-item>
        <el-form-item label="姓名" prop="contactName" >
          <el-input v-model="helpOrderForm.contactName" placeholder="请输入姓名" style="width: 50%" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactPhone" >
          <el-input v-model="helpOrderForm.contactPhone" placeholder="请输入联系方式" style="width: 50%" />
        </el-form-item>
        <el-form-item label="特殊需求" prop="specialNeeds" >
          <el-input v-model="helpOrderForm.specialNeeds" type="textarea" placeholder="请输入特殊需求" style="width: 50%" />
        </el-form-item>
        <div style="text-align: center;margin-top: 70px">
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>

</template>

<script>
import {
  listMessageConversation
} from '@/api/biz/messageConversation'
import { setMessageReadByConversationId, listMessageLog, setMessageReadById } from '@/api/biz/messageLog'
import { getInfo } from '@/api/login'
import { getToken } from '@/utils/auth'
import { getUserListByType } from '@/api/biz/escort'
import { getProductList } from '@/api/biz/service'
import { getServiceHospitalList } from '@/api/biz/hospital'
import { createHelpCustomerOrder } from '@/api/biz/serviceOrder'

export default {
  name: 'MessageConversation',
  dicts: ['sys_user_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 聊天会话表格数据
      messageConversationList: [],
      messageLogList: [],
      userList: [],
      productList: [],
      hospitalList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      helpOrderOpen: false,
      // 查询参数
      queryParams: {
        sendUserId: undefined,
        receiveUserId: undefined,
        sendUnreadCount: undefined,
        receiveUnreadCount: undefined,
        sendUserName: undefined
      },
      messageLogQueryParams: {
        sendUserId: undefined,
        receiveUserId: undefined,
        conversationId: undefined
      },
      userQueryParams: {
        hospitalIds: [],
        userType: undefined
      },
      picupload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/uploadObs'
      },
      // 表单参数
      form: {},
      helpOrderForm: {},
      price:undefined,
      submitLoading: false,
      userId: undefined,
      messageSocket: undefined,
      lockReconnect: false,//是否真正建立连接
      timeout: 15 * 1000,//15秒一次心跳
      timeoutObj: null,//心跳心跳倒计时
      serverTimeoutObj: null,//心跳倒计时
      timeOutNum: null,//断开 重连倒计时
      detailFlag: false,
      listFlag: true,
      show: true,
      circle: false,
      sendUserName: undefined,
      conversationInitUserId: undefined,
      conversationId: undefined,
      chatTxt: undefined,
      txtVal: 200,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      // 表单校验
      rules: {
        sendUserId: [
          { required: true, message: '发送人id不能为空', trigger: 'blur' }
        ],
        receiveUserId: [
          { required: true, message: '接收人id不能为空', trigger: 'blur' }
        ],
        orderType: [
          { required: true, message: '服务类型不能为空', trigger: 'blur' }
        ],
        acceptUserId: [
          { required: true, message: '服务人员不能为空', trigger: 'blur' }
        ],
        buyType: [
          { required: true, message: '购买类型不能为空', trigger: 'blur' }
        ],
        productId: [
          { required: true, message: '所选服务不能为空', trigger: 'blur' }
        ],
        appointmentDate: [
          { required: true, message: '预约时间不能为空', trigger: 'blur' }
        ],
        hospitalId: [
          { required: true, message: '预约医院不能为空', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '订单金额不能为空', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '订单数量不能为空', trigger: 'blur' }
        ],
        contactName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' }
        ],

      }
    }
  },
  created() {
    this.getUserInfo()
    this.getList()
  },
  methods: {
    /** 查询聊天会话列表 */
    getList() {
      this.loading = true
      listMessageConversation(this.queryParams).then(response => {
        this.messageConversationList = response.data
        this.loading = false
      })
    },
    getUserListByType() {
      getUserListByType(this.userQueryParams).then(res => {
        this.userList = res.data
      })
    },
    channelInputLimit(e) {
      e.returnValue = ''
    },
    // 取消按钮
    cancel() {
      this.helpOrderOpen = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sendUserId: null,
        receiveUserId: null,
        sendUnreadCount: null,
        receiveUnreadCount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm('form')
    },
    helpOrderReset() {
      this.helpOrderForm = {
        orderType: null,
        userId: null,
        type: null,
        appointmentDate: null,
        hospitalId: null,
        contactPhone: null,
        contactName: null,
        specialNeeds: null,
        buyType: null,
        productId: null,
        amount: null,
        num: 1,
        acceptUserId:null
      }
      this.resetForm('helpOrderForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    getUserInfo() {
      getInfo().then(res => {
        this.userId = res.user.userId
        if (res.user.userId !== 1) {
          //超管不需要socket
          this.initSocket()
        }

      })
    },
    chatDetail(row) {
      this.show = false
      this.listFlag = false
      this.detailFlag = true
      this.sendUserName = row.sendUserName
      this.conversationInitUserId = row.sendUserId
      if (row.receiveUnreadCount > 0) {
        //根据会话id设置消息已读
        setMessageReadByConversationId(row.id).then(res => {
        })
      }
      this.messageLogQueryParams.conversationId = row.id
      this.getMessageLogList()
    },
    getMessageLogList() {
      listMessageLog(this.messageLogQueryParams).then(res => {
        this.messageLogList = res.rows
      })
    },

    showList() {
      this.show = true
      this.listFlag = true
      this.detailFlag = false
      //重新请求会话列表
      this.getList()
    },
    descInput() {
      this.txtVal = 200 - this.chatTxt.length
    },
    sendMessage() {
      console.log("fffff", encodeURIComponent(this.chatTxt))
      if (!this.chatTxt || this.chatTxt.trim().length < 1) {
        this.chatTxt = "";
        this.$modal.msgError('请输入内容');
        return;
      }
      let data = {
        sendUserId: this.userId,
        content: this.chatTxt.trim(),
        type: '1',
        receiveUserId: this.conversationInitUserId
      }
      this.messageSocket.send(JSON.stringify(data))
      this.chatTxt = ''
      this.txtVal = 200
      setTimeout(() => {
        this.getMessageLogList()
      }, 500)
    },

    initSocket() {
      //实例化
      // this.messageSocket = new WebSocket('wss://pyw.peiyiyiliao.com/api/messageServer/' + this.userId)
      //this.messageSocket = new WebSocket('ws://test.peiyiyiliao.com/prod-api/api/messageServer/' + this.userId)
      this.messageSocket = new WebSocket('ws://127.0.0.1:9274/api/messageServer/' + this.userId)
      if (!this.messageSocket) {
        console.log('您的浏览器不支持websocket协议！')
        return
      }
      // 开启服务器
      this.messageSocket.onopen = () => {
        console.log('用户id=>' + this.userId + ' 进行websocket已链接且连接成功.')
        this.start()
      }
      this.messageSocket.onmessage = (e) => {
        console.log(e, 'e就是返回的数据')
        let data = JSON.parse(e.data)
        if (data.type == 0) {
          this.resetHeartCheck()
        } else {
          if (this.listFlag && !this.detailFlag) {
            //收到的消息不是自己发的，才需要消息处理
            if (data.sendUserId !== this.userId) {
              console.log("this.messageConversationList", this.messageConversationList);
              this.messageConversationList.forEach(item => {
                if (item.receiveUserId == data.receiveUserId && item.sendUserId == data.sendUserId) {
                  item.receiveUnreadCount = item.receiveUnreadCount + 1
                  let temporaryArray = []
                  let currentIdx = this.messageConversationList.findIndex(v => v.receiveUserId == data.receiveUserId)
                  temporaryArray.push(this.messageConversationList[currentIdx])
                  this.messageConversationList.splice(currentIdx, 1)
                  //重新渲染数组
                  this.messageConversationList = temporaryArray.concat(this.messageConversationList)
                }
              })
            }
          } else if (!this.listFlag && this.detailFlag) {
            listMessageLog(this.messageLogQueryParams).then(res => {
              this.messageLogList = res.rows
              if (data.sendUserId !== this.userId) {
                //设置这一条消息已读
                let message = this.messageLogList[this.messageLogList.length - 1]
                setMessageReadById(message.id).then(res => {
                })
              }
            })

          }
        }
      }
      // 关闭服务器
      this.messageSocket.onclose = () => {
        console.log('websocket连接已关闭...')
      }
    },
    //开启心跳
    start() {
      console.log('开启心跳')
      let self = this
      self.timeoutObj && clearTimeout(self.timeoutObj)
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
      self.timeoutObj = setTimeout(function() {
        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (self.messageSocket.readyState == 1) {//如果连接正常
          let msg = {
            type: 0,
            receiveUserId: self.userId,
            sendUserId: self.userId,
            content: 'reconnect'
          }
          self.messageSocket.send(JSON.stringify(msg))
        } else {//否则重连
          self.reconnect()
        }
        self.serverTimeoutObj = setTimeout(function() {
          //超时关闭
          self.messageSocket.close()
        }, self.timeout)

      }, self.timeout)
    },
    //重新连接
    reconnect() {
      console.log('重新连接')
      let that = this
      if (that.lockReconnect) {
        return
      }
      that.lockReconnect = true
      //没连接上会一直重连，设置延迟避免请求过多
      that.timeOutNum && clearTimeout(that.timeOutNum)
      that.timeOutNum = setTimeout(function() {
        //新连接
        that.initSocket()
        that.lockReconnect = false
      }, 5000)
    },
    //重置心跳
    resetHeartCheck() {
      let that = this
      //清除时间
      clearTimeout(that.timeoutObj)
      clearTimeout(that.serverTimeoutObj)
      //重启心跳
      that.start()
    },
    // 文件上传中处理
    handleChatUploadProgress(event, file, fileList) {
      this.picupload.isUploading = true
    },
    // 文件上传成功处理
    handleChatSuccess(response, file, fileList) {
      this.picupload.open = false
      this.picupload.isUploading = false
      if (response.code === 200) {
        let data = {
          type: 2,
          receiveUserId: this.conversationInitUserId,
          sendUserId: this.userId,
          content: response.data.url
        }
        this.messageSocket.send(JSON.stringify(data))
        setTimeout(() => {
          this.getMessageLogList()
        }, 500)
      }
    },
    helpCustomerOrder() {
      console.log('代客户下单')
      this.helpOrderReset();
      this.helpOrderOpen = true
    },
    /**选择服务人员*/
    selectServiceUser(userType) {
      this.$set(this.helpOrderForm, 'acceptUserId', undefined)
      this.$set(this.helpOrderForm, 'productId', undefined)
      this.$set(this.helpOrderForm, 'buyType', undefined)
      this.$set(this.helpOrderForm, 'hospitalId', undefined)
      this.$set(this.helpOrderForm, 'amount', undefined)
      this.userQueryParams.userType = userType
      getUserListByType(this.userQueryParams).then(res => {
        this.userList = res.data
      })
    },
    clearProductInfo(){
      this.$set(this.helpOrderForm, 'productId', undefined)
      this.$set(this.helpOrderForm, 'buyType', undefined)
      this.$set(this.helpOrderForm, 'amount', undefined)
      this.$set(this.helpOrderForm, 'hospitalId', undefined)
    },
    /**选择服务或套餐列表*/
    selectServiceList(buyType){
      this.$set(this.helpOrderForm, 'productId', undefined)
      this.$set(this.helpOrderForm, 'hospitalId', undefined)
      this.$set(this.helpOrderForm, 'amount', undefined)
      getProductList({ userId:this.helpOrderForm.acceptUserId, buyType:buyType}).then(res =>{
          this.productList = res.data;
      });
    },
    selectHospital(){
      let product = this.productList.filter(item =>{
        return item.id === this.helpOrderForm.productId
      })
      this.helpOrderForm.amount = product[0].price;
      this.price = this.helpOrderForm.amount;
      this.$set(this.helpOrderForm, 'hospitalId', undefined)
      getServiceHospitalList({id:this.helpOrderForm.productId,type:this.helpOrderForm.buyType}).then(res =>{
        this.hospitalList = res.data;
      })
    },
    handleAddAmount(val){
      if(this.price !== undefined){
        this.helpOrderForm.amount = this.price * val;
      }
    },
    submitForm(){
      console.log("this.conversationInitUserId",this.conversationInitUserId);
      this.$refs["helpOrderForm"].validate(valid => {
        if (valid) {
          this.helpOrderForm.userId = this.conversationInitUserId;
          this.submitLoading = true
          console.log("this.helpOrderForm",this.helpOrderForm);
          createHelpCustomerOrder(this.helpOrderForm).then(response => {
            this.$modal.msgSuccess('下单成功')
            this.helpOrderOpen = false
            this.submitLoading = false
          }).catch(() => {
            this.submitLoading = false
          })
        }
      });
    }
  },
  directives: {
    scroll: {
      bind(el, binding, vnode) {
        const pause = (e) => {
          let auto = binding.value ? binding.value.auto : false
          let scrolled = el.scrollTop + el.clientHeight + 1 < el.scrollHeight
          let timeout
          window.clearTimeout(timeout)
          timeout = setTimeout(() => {
            if (auto && scrolled) {
              el.setAttribute('v-scroll2-manually', 'yes')
            } else if (auto && !scrolled) {
              el.setAttribute('v-scroll2-manually', '')
            } else {
              el.removeEventListener('scroll', pause)
            }
          }, 600)
        }
        el.addEventListener('scroll', pause)
      },
      update(el, binding, vnode) {
        if (!el.getAttribute('v-scroll2-manually')) {
          vnode.context.$nextTick(() => {
            el.scrollTop = el.scrollHeight - el.clientHeight
          })
        }
      }
    }
  }
}
</script>
<style lang="scss">

.num {
  position: absolute;
  right: 0;
  top: 8px;

  span {
    color: #fff;
    font-size: 14px;
    background-color: red;
    padding: 4px 8px;
    border-radius: 20px;
  }

}

.el-upload-dragger {
  width: 40px;
  height: 30px;
  margin-top: 3px;
}

.left {
  flex: 1;
  display: flex;
  height: 750px;
  margin-right: 10px;

  .chat-area {
    width: 100%;
    height: 100%;

    .right-chat-box {
      border: 1px solid #D7D7D7;
      box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.1);
      border-radius: 4px;
      background-color: #fff;
      height: 100%;
      min-width: 571px;
      padding: 10px 21px 19px 21px;

      .nav-title {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 40px;
        background-color: #D3D3D3;
        margin-bottom: 10px;
        position: relative;
      }

      i {
        position: absolute;
        left: 10px;
        top: 6px;
      }

      .r-item {
        width: 100%;
        height: 351px;
        display: none;
      }

      .show {
        display: block;
      }

      #chat-area {
        padding: 20px;
        height: 440px;
        background: #F2F2F2;
        border-radius: 4px;
        overflow-y: auto;

        .item {
          overflow: hidden;
          margin-top: 20px !important;
        }

        .item:first-child {
          margin-top: unset;
        }

        .item-left {
          box-sizing: border-box;
          padding-left: 25px;
          position: relative;

          div {
            float: left;
          }

          .il-check {
            position: absolute;
            top: 50%;
            left: 0;
            transform: translateY(-50%);

            .el-checkbox__inner {
              width: 20px;
              height: 20px;
            }

            .el-checkbox__inner::after {
              width: 5px;
              height: 13px;
              left: 6px;
            }
          }

          .avatar {
            width: 38px;
            height: 38px;
            /*background: #FFCCCC;*/
            border-radius: 4px;

            img {
              width: 100%;
              height: 100%;
            }
          }

          .item-content {
            position: relative;
            margin-left: 14px;
            padding: 11px 14px 13px 16px;
            background-color: #ffff;
            border-radius: 4px;
            max-width: 60%;
            word-break: break-all;

            &.file {
              width: 90px;
            }

            &::before {
              position: absolute;
              content: '';
              width: 0;
              height: 0;
              border: 4px;
              border-style: solid;
              border-color: transparent #fff transparent transparent;
              left: -8px;
              top: 18px;
            }

            > div {
              float: unset;
              display: flex;
              flex-direction: column;

              > div {
                float: unset;

                &.remark {
                  text-align: center;
                  font-size: 12px;
                  color: #999;
                }
              }
            }
          }
        }

        .item-right {
          width: 100%;
          box-sizing: border-box;
          padding-left: 25px;
          position: relative;

          div {
            float: right;
          }

          .il-check {
            position: absolute;
            top: 50%;
            left: 0;
            transform: translateY(-50%);

            .el-checkbox__inner {
              width: 20px;
              height: 20px;
            }

            .el-checkbox__inner::after {
              width: 5px;
              height: 13px;
              left: 6px;
            }
          }

          .avatar {
            width: 38px;
            height: 38px;
            /*background: #FFCCCC;*/
            border-radius: 4px;

            img {
              width: 100%;
              height: 100%;
            }
          }

          .item-content {
            position: relative;
            margin-right: 14px;
            padding: 11px 14px 13px 16px;
            background-color: #ffff;
            border-radius: 4px;
            max-width: 60%;
            word-break: break-all;

            &.file {
              width: 90px;
            }

            &::after {
              position: absolute;
              content: '';
              width: 0;
              height: 0;
              border: 4px;
              border-style: solid;
              border-color: transparent transparent transparent #fff;
              right: -8px;
              top: 18px;
            }

            > div {
              float: unset;
              display: flex;
              flex-direction: column;

              > div {
                float: unset;

                &.remark {
                  text-align: center;
                  font-size: 12px;
                  color: #999;
                }
              }
            }
          }
        }
      }

      .tool {
        display: flex;
        align-items: center;
        margin-top: 10px;
        height: 40px;
        background-color: #999999;
      }

      .text-area {
        position: relative;

        textarea {
          resize: none;
          width: 100%;
          margin-top: 5px;
          height: 115px;
          background: #FFFFFF;
          border: 1px solid #B3B3B3;
          border-radius: 4px;
          overflow-y: auto;
          padding: 10px;
        }
      }

      .btn {
        margin-top: 10px;
        float: right;
        width: 60px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        background: #8F2821;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 400;
        color: #FFFFFF;
      }

      .orderBtn {
        margin-top: 10px;
        float: right;
        width: 110px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        background: #8F2821;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 400;
        color: #FFFFFF;
      }
    }
  }
}

.upload-box {
  display: flex;
  align-items: center;
}
</style>

